package com.share.admin.config.security;

import com.share.admin.constant.SysConstant;
import com.share.admin.model.db.User;
import com.share.admin.service.IMenuService;
import com.share.admin.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 在登录的时候会使用这个类
 */
@Component("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IMenuService iMenuService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        User user = iUserService.getByAccount(account);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        //查询到这个用户的所有菜单与按钮权限
        Set<String> permissions = null;
        if (SysConstant.ADMIN.equals(account)) {
            permissions = iMenuService.permissionAll();
        } else {
            permissions = iMenuService.permissionByUserId(user.getId());
        }

        //创建securty内置的user对象
        LoginUser loginUser = new LoginUser(user, permissions);
        return loginUser;
    }
}
